package com.fire.service;

import com.fire.common.domain.BusinessException;
import com.fire.common.domain.CommonErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fire
 * @date 2021年07月11日9:46
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${sms.url}")
    String url;
    @Value("${sms.effectiveTime}")
    String effectiveTime;

    @Override
    public String sendMsg(String phone) {
        String sms_url = url+"/generate?name=sms&effectiveTime="+effectiveTime;
        //        请求信息：body and header
        Map<String,Object> body = new HashMap<>();
        body.put("mobile",phone);

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map> entity = new HttpEntity<Map>(body, header);

        ResponseEntity<Map> exchange = null ;
        Map bodyMap;
        try {
            exchange = restTemplate.exchange(sms_url, HttpMethod.POST, entity, Map.class);
            log.info("请求验证码服务，得到响应：{}",exchange);
            bodyMap = exchange.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            throw  new RuntimeException("发送验证码失败");
        }
        if (bodyMap==null || bodyMap.get("result")==null){
            throw  new RuntimeException("发送验证码失败");
        }

        Map result = (Map) bodyMap.get("result");
        String key = (String) result.get("key");
        log.info("得到验证码发送对应的key:{}",key);
        return key;
    }

    @Override
    public void verify(String verifyKey, String verifyCode) throws BusinessException {
//        校验验证码的url
        String url = "http://localhost:56085/sailing/verify?name=sms&verificationCode="+verifyCode+"&verificationKey="+verifyKey;
        Map bodyMap = null;

        try{
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            bodyMap = exchange.getBody();
        }catch (Exception e){
//            throw  new RuntimeException("校验验证码失败");
            throw new BusinessException(CommonErrorCode.E_100102);
        }

        if (bodyMap==null || bodyMap.get("result")==null || (boolean)bodyMap.get("result")!=true){
//            throw  new RuntimeException("校验验证码失败");
            throw new BusinessException(CommonErrorCode.E_100102);
        }

    }
}
